﻿using Metabase;
using Metabase.MetabaseObjects;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ApplicationGUI.ChildForms
{
    public partial class MetabaseForm : Form
    {
        public MetabaseHandler metabaseHandler;
        public MetabaseObject selectedObject;
        public TreeNode selectedNode;

        // Функция рекурсивного поиска нода по по objectItem.ID
        private TreeNode FindParentNode(int Parent_ID, TreeNode StartNode)
        {
            while (StartNode != null)
            {
                if ((int)(StartNode.Tag as MetabaseObject).ID == Parent_ID) return StartNode;
                if (StartNode.Nodes.Count != 0)
                {
                    TreeNode currentNode = FindParentNode(Parent_ID, StartNode.Nodes[0]);
                    if (currentNode != null) return currentNode;
                };
                StartNode = StartNode.NextNode;
            }
            return null;
        }
        
        // Процедура отрисовки дерева структуры метаданных
        private void ShowMetaDataTree()
        {
            MetabaseTreeView.BeginUpdate();
            MetabaseTreeView.Nodes.Clear();
            List<MetabaseObject> objectList = metabaseHandler.GetMetabaseObjectList();
            foreach (MetabaseObject objectItem in objectList)
            {
                TreeNode currentNode = new TreeNode { Text = (string)objectItem.Object_Name, Tag = objectItem, ImageIndex = (int)objectItem.Type_ID, SelectedImageIndex = (int)objectItem.Type_ID };
                if (objectItem.Parent_ID is DBNull) MetabaseTreeView.Nodes.Add(currentNode);
                else
                {
                    if (MetabaseTreeView.Nodes.Count > 0)
                    {
                        TreeNode parentNode = FindParentNode((int)objectItem.Parent_ID, MetabaseTreeView.Nodes[0]);
                        if (parentNode == null) MetabaseTreeView.Nodes.Add(currentNode);
                        else parentNode.Nodes.Add(currentNode);
                    }
                    else MetabaseTreeView.Nodes.Add(currentNode);
                }
            }
            if (MetabaseTreeView.Nodes.Count > 0) MetabaseTreeView.SelectedNode = MetabaseTreeView.Nodes[0];
            MetabaseTreeView.EndUpdate();
        }
        
        public void InitMetabase()
        {
            metabaseHandler.InitMetabase();
            this.Text = metabaseHandler.MetabaseName;
            ShowMetaDataTree();
        }

        public MetabaseForm()
        {
            InitializeComponent();
        }

        // Процедура заполнения списка дочерних элементов
        private void ShowChildElements(MetabaseObject parentObject)
        {
            if (parentObject == null) return;
            listViewChildInfo.Items.Clear();
            List<MetabaseObject> objectList = metabaseHandler.GetMetabaseObjectList(parentObject);
            listViewChildInfo.BeginUpdate();
            foreach (MetabaseObject objectItem in objectList)
            {
                ListViewItem newItem = listViewChildInfo.Items.Add(objectItem.ID.ToString());
                newItem.SubItems.Add((string)objectItem.Object_Name);
                newItem.SubItems.Add(objectItem.External_ID.ToString());
                newItem.SubItems.Add(objectItem.Type_Name.ToString());
                newItem.SubItems.Add(objectItem.Modify_Date.ToString());
                newItem.ImageIndex = (int)objectItem.Type_ID;
                //var newItem = new ListViewItem(new[] { objectItem.ID, objectItem.Object_Name, objectItem.External_ID, objectItem.Type_ID, null });
            }
            listViewChildInfo.EndUpdate();
        }
        
        private void MetabaseTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (MetabaseTreeView.SelectedNode.Tag is MetabaseObject) selectedObject = MetabaseTreeView.SelectedNode.Tag as MetabaseObject;
            else selectedObject = null;
            selectedNode = MetabaseTreeView.SelectedNode;
            // Заполним список справа дочерними элементами
            ShowChildElements(selectedNode.Tag as MetabaseObject);
        }

        private void deleteSelectedItemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MetabaseOperations.DeleteObjectItem(metabaseHandler, selectedObject, selectedNode);
        }

        private void createFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectedNode == null) return;
            TreeNode newNode = selectedNode.Nodes.Add(AppResources.NewFolderName);
            newNode.Parent.Expand();
            newNode.ImageIndex = (int)ObjectTypes.otFolder;
            newNode.SelectedImageIndex = (int)ObjectTypes.otFolder;
            newNode.TreeView.SelectedNode = newNode;
            newNode.BeginEdit();
        }

        private void MetabaseTreeView_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (!String.IsNullOrEmpty(e.Label))
            {
                selectedNode.Text = e.Label;
            }
            if (selectedNode.Tag == null)
            {
                MetabaseOperations.CreateObjectItem(metabaseHandler, selectedNode, ObjectTypes.otFolder);
            }
            else
            {
                MetabaseOperations.UpdateObjectItem(selectedNode);
            }
        }

        private void refreshStructureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InitMetabase();
        }

        // Процедура инициализации дочерних объектов
        private void initlistViewChildInfo()
        {
            listViewChildInfo.Columns.Clear();
            // TODO - сделать чтение настройки из файла параметров
            listViewChildInfo.Columns.Add(AppResources.ColumnID, 60, HorizontalAlignment.Right);
            listViewChildInfo.Columns.Add(AppResources.ColumnName, -2, HorizontalAlignment.Left);
            listViewChildInfo.Columns.Add(AppResources.ColumnExternalID, -2, HorizontalAlignment.Left);
            listViewChildInfo.Columns.Add(AppResources.ColumnType, -2, HorizontalAlignment.Left);
            listViewChildInfo.Columns.Add(AppResources.ColumnModifyDate, -2, HorizontalAlignment.Center);
        }
        
        private void MetabaseForm_Load(object sender, EventArgs e)
        {
            // Инициализируем ListView для показа дочерних объектов
            initlistViewChildInfo();
        }

        private void dictionaryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EditDictionaryForm Form = new EditDictionaryForm();
            Form.ShowDialog();
        }
    }
}
